package br.com.fatecpg.projetohoroscopo.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;
import android.widget.TextView;

public class RequestTask extends AsyncTask<String, Void, String> {

	private TextView view;

	public RequestTask(TextView view) {
		this.view = view;
	}

	@Override
	protected String doInBackground(String... url) {
		String retorno = "";

		try {
			HttpClient httpCli = new DefaultHttpClient();
			HttpResponse httpRes = httpCli.execute(new HttpGet(url[0]));
			StatusLine status = httpRes.getStatusLine();

			if (status.getStatusCode() == HttpStatus.SC_OK) {
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				httpRes.getEntity().writeTo(out);
				retorno = out.toString();
				out.close();

				return retorno;
			} else {
				httpRes.getEntity().getContent().close();
				throw new Exception(status.getReasonPhrase());
			}
		} catch (ClientProtocolException e) {
			try {
				throw new Exception(e.getMessage());
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} catch (IOException e) {
			try {
				throw new Exception(e.getMessage());
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return retorno;
	}

	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);

		try {
			new HtmlStringUtils().setPrevisaoHoroscopo(view, result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
